const config_module = require('./config')
const Redis = require("ioredis")

// 创建Redis客户端的实例
const RedisCli = new Redis({
    host: config_module.redis_host,
    port: config_module.redis_port,
    password: config_module.redis_passwd
});

// 错误信息监听
RedisCli.on("error",function(err){
    console.log("RedisCli connect eorror");
    RedisCli.quit();
});

// GetValue
async function GetRedis(key){
    try{
        const result = await RedisCli.get(key);
        if(result == null){
            console.log("result:<",result,"> This key can't be find...");
            return null;
        }
        console.log("result:<",result,"> Get key success...");
        return result;
    }catch(error){
        console.log("GetRedis error is",error);
        return null;
    }
}

// FindKey
async function QueryRedis(key){
    try{
        const result = await RedisCli.exists(key);
        // 判断值是否为空
        if(result === 0){
            console.log("result:<",result,"> This key is null...");
            return null;
        }
        console.log("result:<",key,"> the value is ",result,"...");
        return result;

    }catch(error){
        console.log("QueryRedis error is",error);
        return null;
    }
}

// 设置key value 和过期时间
async function SetRedisExpire(key,value,exptime){
    try{
        // 设置键值
        await RedisCli.set(key,value);
        // 设置过期时间
        await RedisCli.expire(key,exptime);
        return true;
    }catch(error){
        console.log("SetRedisExpire error is",error);
        return null;
    }
}

// 退出
function Quit(){
    RedisCli.quit();
}

module.exports = {
    GetRedis,
    QueryRedis,
    Quit,
    SetRedisExpire
} 